<template>
  <div>
    <!-- 顶部导航栏 -->
    <div class="Navigation_top">
      <!-- 返回的盒子 -->
      <div class="get_back_box">
        <router-link to="/">
          <img src="../assets/return.png" alt="">
        </router-link>
        <div class="line"></div>
        <router-link to="/">
          <img src="../assets/home.png" alt="">
        </router-link>
      </div>
      <p>景区地图</p>
    </div>
    <!-- 底部选项 -->
    <div class="Navigation_bottom">
      <!-- 整体的选项盒子 -->
      <div class="option_box">
        <div class="option_single">
          <div class="highlight"></div>
          景区
        </div>
        <div class="option_single">
          休息点
        </div>
        <div class="option_single">
          停车场
        </div>
        <div class="option_single">
          卫生间
        </div>
        <div class="option_single">
          景区
        </div>
      </div>
      <img src="../assets/widgets.png" alt="">
    </div>
    <!-- 地图 -->
    <div id="container">
      <!-- 工具栏 -->
      <div class="tool_box">
        <router-link to="map">
          <div>
            <img src="../assets/refresh.png" alt="">
            刷新
          </div>
        </router-link>
        <div class="gap"></div>
        <div @click="goToCurrentLocation">
          <img src="../assets/location.png" alt="">
          定位
        </div>
      </div>
    </div>
    <div id="panel" style="width: 300px; height: 200px;"></div> <!-- 路线结果面板 -->
  </div>
</template>

<script setup>
import AMapLoader from '@amap/amap-jsapi-loader';
import { ref, onMounted } from 'vue';
import { mapPath } from '../api/scenic.js';

const lat = ref(null);
const lng = ref(null);
const map = ref(null); // 使用 ref 管理地图实例
const currentMarker = ref(null);
const markers = ref([]);
const currentCenter = ref(null);
// 正确定义起点经纬度（经度在前，纬度在后）
const origin_lng = ref(116.379028); // 经度
const origin_lat = ref(39.865042);  // 纬度

window._AMapSecurityConfig = {
  securityJsCode: "c243f95c7b6503157150489e2206e17b",
};

onMounted(async () => {
  try {
    // 1. 获取目的地坐标
    const res = await mapPath({ map_id: 10 });
    lat.value = res.data[0].lat;
    lng.value = res.data[0].lng;
    console.log('目的地坐标:', lng.value, lat.value); // 验证数据

    // 2. 加载高德地图API
    const AMap = await AMapLoader.load({
      key: "6df9de29656128c56fe25f6da02b9f5c",
      version: "2.0",
      plugins: ["AMap.Driving", "AMap.Geolocation", "AMap.Scale", "AMap.DragRoute"]
    });

    // 3. 初始化地图
    map.value = new AMap.Map("container", {
      viewMode: "2D",
      zoom: 11,
      center: [origin_lng.value, origin_lat.value] // 初始中心点为起点
    });

    // 4. 路线规划
    const driving = new AMap.Driving({
      map: map.value,
      panel: "panel"
    });

    driving.search(
      new AMap.LngLat(origin_lng.value, origin_lat.value), // 起点 (经度, 纬度)
      new AMap.LngLat(lng.value, lat.value),               // 终点 (经度, 纬度)
      (status, result) => {
        if (status === 'complete') {
          console.log('路线规划完成');
          map.value.setCenter([origin_lng.value, origin_lat.value]);
        } else {
          console.error('失败原因:', result);
        }
      }
    );
  } catch (e) {
    console.error('初始化失败:', e);
  }
});

const goToCurrentLocation = () => {
  console.log('开始定位');
  if (map.value && window.AMap) {
    const geolocation = new window.AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 5000, // 延长超时时间
      buttonOffset: new window.AMap.Pixel(10, 20),
      zoomToAccuracy: true,
    });
    // 发起定位
    geolocation.getCurrentPosition((status, result) => {
      console.log('定位状态:', status, '结果:', result);
      if (status === 'complete') {
        const position = result.position;
        map.value.setCenter(position);
        currentCenter.value = position;

        // 清理旧标记
        if (currentMarker.value) {
          currentMarker.value.setMap(null);
        }
        origin_lng.value = position.lng; // 经度
        origin_lat.value = position.lat;  // 纬度

        // 添加新标记
        currentMarker.value = new window.AMap.Marker({
          position: position,
          map: map.value
        });
        markers.value.push(currentMarker.value);
      } else {
        console.error('定位失败:', result.message || result);
      }
    });
  } else {
    console.error('地图未初始化或 AMap 未加载');
  }
};
</script>

<style scoped>
a {
  display: inline;
  width: auto;
  height: 35px;
  min-width: 0;
  min-height: 0;
  padding: 0;
  margin: 0;
  color: black;
  text-decoration: none;
  /* 可选：移除下划线 */
}

/* 导航栏 */
.Navigation_top {
  width: 100%;
  height: 40px;
  text-align: center;
  position: relative;
  line-height: 40px;
  border-bottom: 1px solid #ccc;
}

/* 返回按钮 */
.get_back_box {
  width: 60px;
  height: 60%;
  display: flex;
  position: absolute;
  align-items: center;
  justify-content: space-around;
  border-radius: 15px;
  margin-top: 8px;
  margin-left: 10px;
  border: #999999 solid 1px;
}

.get_back_box img {
  width: 18px;
}

/* 分割线 */
.line {
  width: 1px;
  height: 60%;
  background-color: #999999;
}

/* 底部导航栏 */
.Navigation_bottom {
  width: 100%;
  padding: 1% 3%;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.Navigation_bottom img {
  width: 20px;
}

/* 单个选项 */
.option_box {
  width: 75%;
  height: 80%;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.option_single {
  position: relative;
}

/* 高亮的下划线 */
.highlight {
  width: 30px;
  height: 5px;
  left: 3%;
  bottom: -5px;
  border-radius: 10px;
  background-color: #2A82E4;
  position: absolute;
}

#container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.tool_box {
  width: 60px;
  height: auto;
  padding: 25px 10px;
  border-radius: 10px;
  background-color: white;
  position: absolute;
  z-index: 10;
  right: 10px;
  top: 30px;
  text-align: center;
}

.tool_box img {
  width: 65%;
}

.gap {
  height: 15px;
}
</style>